from django.db import models
from django.urls import reverse
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey


class EquipmentModel(models.Model):
    '''
    设备公共信息
    抽象类
    '''
    brand = models.CharField(max_length=200, verbose_name='品牌')
    name = models.CharField(max_length=200, verbose_name='型号')
    feature = models.CharField(max_length=200, null=True, blank=True, verbose_name='特征字段')
    total_quantity = models.PositiveSmallIntegerField(default=0, verbose_name='总数')
    online_quantity = models.PositiveSmallIntegerField(default=0, verbose_name='在用')
    instock_quantity = models.PositiveSmallIntegerField(default=0, verbose_name='库存数')
    damage_quantity = models.PositiveSmallIntegerField(default=0, verbose_name='损坏数')
    lend_quantity = models.PositiveSmallIntegerField(default=0, verbose_name='借出数')
    remark = models.TextField(null=True, blank=True, verbose_name='备注')

    class Meta:
        abstract = True
        unique_together = ('brand', 'name', 'feature',)

    def __str__(self):
        return self.name


class PowerSupplyModel(EquipmentModel):
    '''
    供电设备
    '''
    STORAGE_BATTERY = 'SB'
    SOLAR_POWER = 'SP'
    SMART_CHARGER = 'SC'
    ACDC_POWER = 'AD'
    OTHER = 'OT'

    POWER_SUPPLY_TYPE = (
        (STORAGE_BATTERY, '电瓶'),
        (SOLAR_POWER, '太阳能'),
        (SMART_CHARGER, '智能充电器'),
        (ACDC_POWER, '开关电源'),
        (OTHER, '其它')
    )

    type = models.CharField(choices=POWER_SUPPLY_TYPE, max_length=6, verbose_name='分类')

    class Meta:
        verbose_name = '供电设备'
        verbose_name_plural = '供电设备'

    def __str__(self):
        return '[{type}] {brand}/{name}'.format(type=self.get_type_display(), brand=self.brand, name=self.name)


class NetworkDeviceModel(EquipmentModel):
    '''
    网络设备
    '''
    ROUTER = 'RT'
    INTERCHANGER = 'IC'
    PHOTOELECTRIC_CONVERTER = 'PEC'
    OTHER = 'OT'

    NETWORK_DEVICE_TYPE = (
        (ROUTER, '路由器'),
        (INTERCHANGER, '交换机'),
        (PHOTOELECTRIC_CONVERTER, '光电转换器'),
        (OTHER, '其它'),
    )

    type = models.CharField(choices=NETWORK_DEVICE_TYPE, max_length=6, verbose_name='分类')

    class Meta:
        verbose_name = '通讯设备'
        verbose_name_plural = '通讯设备'

    def __str__(self):
        return '[{type}] {brand}/{name}'.format(type=self.get_type_display(), brand=self.brand, name=self.name)


class AccessoriesModel(EquipmentModel):
    '''
    设备配件
    '''
    GPS_ANTENNA = 'GPS'
    GPS_LINE = 'GL'
    SENSOR_LINE = 'SL'
    DATA_LINE = 'DL'
    OTHER = 'OT'

    ACCESSORIES_TYPE = (
        (GPS_ANTENNA, 'GPS天线'),
        (GPS_LINE, 'GPS连接线'),
        (DATA_LINE, '数据传输线'),
        (SENSOR_LINE, '摆线'),
        (OTHER, '其它'),
    )

    type = models.CharField(choices=ACCESSORIES_TYPE, max_length=6, verbose_name='分类')

    class Meta:
        verbose_name = '重要配件'
        verbose_name_plural = '重要配件'

    def __str__(self):
        return '[{type}] {brand}/{name}'.format(type=self.get_type_display(), brand=self.brand, name=self.name)


class SeismicEquipmentModel(EquipmentModel):
    '''
    测震设备
    '''
    SENSOR = 'SS'
    DATALOGGING = 'DL'
    ALL_IN_ONE = 'AIO'
    OTHER = 'OT'

    SEISMIC_EQUIPMENT_TYPE = (
        (SENSOR, '测震仪'),
        (DATALOGGING, '数据采集器'),
        (ALL_IN_ONE, '一体机'),
        (OTHER, '其它'),
    )

    type = models.CharField(choices=SEISMIC_EQUIPMENT_TYPE, max_length=6, verbose_name='分类')

    # accessories = models.ManyToManyField('AccessoriesModel', verbose_name='重要配件')

    class Meta:
        verbose_name = '测震仪器型号'
        verbose_name_plural = '测震仪器型号'

    def __str__(self):
        feature = "/{}".format(self.feature)
        if not self.feature:
            feature = ""

        return '[{type}] {brand} {name}{feature}'.format(type=self.get_type_display(), brand=self.brand,
                                                         name=self.name, feature=feature)


class SeismicEquipmentEntity(models.Model):
    STATUS_TYPE = (
        ('STOCK', '库存'),
        ('ONLINE', '在线'),
        ('UNDER_DETECTION', '待检测'),
        ('BREAKDOWN', '故障'),
        ('REPAIR', '返修'),
    )

    sn = models.CharField(max_length=20)
    model = models.ForeignKey(SeismicEquipmentModel, on_delete=models.DO_NOTHING)
    status = models.CharField(choices=STATUS_TYPE, max_length=20, default='STOCK')
    belong_list = models.ForeignKey('EquipmentList', on_delete=models.SET_NULL, null=True, blank=True,
                                    related_name="seismic_equipment_entities")

    class Meta:
        verbose_name = '测震仪器实体'
        verbose_name_plural = '测震仪器实体'
        unique_together = ('sn', 'model')

    def __str__(self):
        return '{model} ({sn})'.format(model=self.model, sn=self.sn)


class EquipmentList(models.Model):
    '''
    台站设备列表(最终)
    '''
    station = models.OneToOneField('seisnet.Station', on_delete=models.CASCADE, verbose_name='所属台站')

    class Meta:
        verbose_name = '台站设备列表'
        verbose_name_plural = '台站设备列表'

    def __str__(self):
        return "{station}'s equipment list".format(station=self.station)

    def get_absolute_url(self):
        return reverse('seisnet:station_detail',
                       kwargs={'network_code': self.station.network.code, 'code': self.station.code})


class ItemManager(models.Manager):
    def powersupply(self):
        ct = ContentType.objects.get_for_model(PowerSupplyModel)
        return self.filter(content_type=ct)

    def networkdevice(self):
        ct = ContentType.objects.get_for_model(NetworkDeviceModel)
        return self.filter(content_type=ct)

    def accessories(self):
        ct = ContentType.objects.get_for_model(AccessoriesModel)
        return self.filter(content_type=ct)


class EquipmentItem(models.Model):
    '''
    所属台站设备名称及个数
    '''
    belong_list = models.ForeignKey('EquipmentList', on_delete=models.CASCADE, null=True, blank=True, related_name="equipment_items")
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
                                     limit_choices_to={
                                         'model__in': ('powersupplymodel', 'networkdevicemodel', 'accessoriesmodel')})
    object_id = models.PositiveIntegerField()
    equipment = GenericForeignKey('content_type', 'object_id')
    quantity = models.PositiveIntegerField(default=1, verbose_name='数量')

    objects = ItemManager()

    class Meta:
        verbose_name = '台站设备条目'
        verbose_name_plural = '台站设备条目'


class AccessoriesItem(models.Model):
    '''
    重要配件条目列表
    '''
    belong_seismodel = models.ForeignKey('SeismicEquipmentModel', on_delete=models.CASCADE, verbose_name='测震仪器配件')
    accessories = models.ForeignKey('AccessoriesModel', on_delete=models.CASCADE, verbose_name='配件列表')
    quantity = models.PositiveIntegerField(default=0, verbose_name='数量')

# class EquipmentModeType(models.Model):
#     '''
#     设备分类
#     '''
#     name = models.CharField(max_length='100', verbose_name='分类名称')
#     parent = models.ForeignKey("EquipmentModeType", null=True, blank=True, verbose_name='父分类')
#     is_unique = models.BooleanField(default=False, verbose_name='设备实体是否有唯一标识')
#
#     class Meta:
#         verbose_name = '设备分类'
#         verbose_name_plural = '设备分类'
